import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Menu,InputNumber,Modal,message,Badge,Divider,Radio,label,Table,} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';


const Option = Select.Option;
const { TextArea } = Input;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');



const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj,successful} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      	form.resetFields();
	    handleAdd(title,obj.userId,fieldsValue);
    });
  };
 const {getFieldDecorator } = form;
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
     title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
   		<Form layout="horizontal">
      		<FormItem label="推广人数"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	            {getFieldDecorator('thresholdNumber', {
	            	initialValue:obj.thresholdNumber,
	              rules: [{ required: true, message: '推广人数不能为空!' }],
	            })(
	              <InputNumber min={1} max={10000000}  placeholder="请输入"  style={{width:'100%',marginLeft:'2px'}}/>
	            )}
          	</FormItem>
          	<FormItem label="返利金额"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	            {getFieldDecorator('thresholdMoney', {
	            	initialValue:obj.thresholdMoney,
	              rules: [{ required: true, message: '返利金额不能为空!' }],
	            })(
	            <InputNumber min={1} max={10000000}  placeholder="请输入" style={{width:'100%',paddingRight:'3px'}}/>
	        )}
          	</FormItem>
    	</Form>
  </Modal>
  );
});



@connect(({ campus, loading }) => ({
  campus,
  loading: loading.models.campus,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    obj: "",
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
       type: 'campus/findpromotion',
    });
  }
   handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'campus/findpromotion',
      payload: params,
    });
    
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
	e.preventDefault();
	const {
		dispatch,
		form
	} = this.props;
	form.validateFields((err, fieldsValue) => {
		if(err) return;
		const values = { ...fieldsValue,
		};
		this.setState({
			formValues: values,
		});
		if(values.operatorName == undefined) values.operatorName = "";
		
		dispatch({
			type: 'campus/findpromote',
			payload: { ...values
			}
		});
	});
};

	

	successful =(record)=>{
		var cashId = record.id;
		var userId = record.userId;
		var isWithdraw = 3;
		var cashType = record.cashType;
		console.log(cashId);
		console.log(userId);
		console.log(isWithdraw);
		this.props.dispatch({
			type: 'campus/addpromotion',
			payload: {
	      	cashId:cashId,
	      	userId:userId,
	      	isWithdraw:isWithdraw,
	      	cashType:cashType
	      },
			callback: (res,resMsg) => {
					if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
		});
		
		
	}

  handleModalVisible = (flag,record,title) => {
  	if(flag==false){
  		this.setState({
	      modalVisible: flag,
	    });
  	}else{
  		var obj="";
	  	if(title!="新建"){
	  		if(record.icon!=undefined){
				
			}
	  		record.state+='';
	  		record.hortationType+='';
	  		obj=record;
	  	}
	    this.setState({
	      modalVisible: !!flag,
	      title: title,
	      obj: obj,
	    });
  	}
  
  };
	/*新增,修改*/
  handleAdd = (title,Id,fields) => {
  	if(title=="新建"){
  		console.log("新建");
	    this.props.dispatch({
	      type: 'campus/addpromote',
	      payload: {...fields,},
	      callback: (res,resMsg) => {        
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
  	}else if(title=="编辑"){
  		this.props.dispatch({
  			type: 'campus/editorpromote',
	      payload: {
	      	...fields,
	      	userId:Id,
	      },
	      callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
  	}
  
    this.setState({
      modalVisible: false,
    });
  };
  
  
  	/*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
    	const { selectedRows } = this.state;
	    if(Id==undefined&&Object.keys(selectedRows).length==0){
	    	message.info("还未选择项");
	    }else{
	    	var Ids=[];
		    if(Id!=undefined){
		    	Ids=Id;
		    }else if(selectedRows!=null){
		    	Ids.push(selectedRows.map(row => row.userId).join(','));
		    }
		    if(title=="删除"){
		    	console.log(Ids);
		    	Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				     onOk() {
				    	dispatch({
				      	type: 'campus/removepromote',
					      payload: {userId:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
		    }
		 	
	    }
 	}
	renderSimpleForm() {
		    const { getFieldDecorator } = this.props.form;
		    return (
		      <Form onSubmit={this.handleSearch} layout="inline">
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		          <Col md={8} sm={24}>
		            <FormItem label="入库单号">
		              {getFieldDecorator('storageID')(<Input placeholder="请输入" />)}
		            </FormItem>
		          </Col>
		          
		          <Col md={8} sm={24}>
		            <FormItem label="供应商">
		              {getFieldDecorator('supplierName')(<Input placeholder="请输入" />)}
		            </FormItem>
		          </Col>
		          <Col md={8} sm={24}>
		            <span className={styles.submitButtons}>
		              <Button type="primary" htmlType="submit">
		                查询
		              </Button>
		              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
		                重置
		              </Button>
		            </span>
		          </Col>
		        </Row>
		      	
		      </Form>
		    );
		  }

	
	
  render() {
    const { campus: { data }, loading } = this.props;
    const { selectedRows, modalVisible,title,obj } = this.state;
    const columns = [
    	{
		title: '序号',
		dataIndex: 'userId',
		key: 'userId',
		render: (text, record, index) => { return index + 1 }
		}, 
		{
		title: '用户姓名',
		dataIndex: 'userName',
		}, 
		{
		title: '提现金额',
		dataIndex: 'cashMoney',
		},
		{
		title: '提现类型',
		dataIndex: ' cashType',
		render: (text, record, index) => {
				if(record.cashType == 1) {
					return "立方币"
				} else if(record.cashType == 2) {
					return "人民币"
				}
			}
		},
		{
		title: '审核状态',
		dataIndex: 'stateName',
		},
		{
		title: '提现时间',
		dataIndex: 'cashDate',
		render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
		},
		{
	    title: '操作',
	    dataIndex: 'state',
	    render: (text, record, index) =>{
	    	if(record.state == 4) {
					return <div>
										<Button type="primary" size="small" onClick={() => this.successful(record)}>成功</Button>
									</div>
				} else{
						return <div>已完成</div>
				}
	    	}
	    },
	 ];
    const parentMethods = {
      handleAdd: this.handleAdd,
      successful: this.successful,
     	handleModalVisible: this.handleModalVisible,
      confirmModel:this.confirmModel,
    };

    return (
    	<PageHeaderLayout title="前台系统/推广记录">
      <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}></div>
            <div className={styles.submitButtons}></div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
      </Card>
      </PageHeaderLayout>
    );
  }
}
